<?php
//require_once ("C_krn_consts.php");
//require_once ("C_krn_exception.php");
require_once ("C_krn_net.php");
require_once ("C_krn_crypt.php");
//require_once ("C_krn_audit.php");

require_once ("external/C_krn_ext_mobile_detect.php");
require_once ("external/C_krn_ext_captcha.php");

require_once("external/class.phpmailer.php");
require_once("external/class.smtp.php");

// Funciones utiles
class c_krn_utils {
	
	// Evitamos el clonaje del objeto. Patrón Singleton
	private function __clone() {
	}
	private function __wakeup() {
	}
	private static $_instance;
	public static function getInstance() {
		if (! (self::$_instance instanceof self)) {
			self::$_instance = new self ();
		}
		
		return self::$_instance;
	}
	function Ver_Supervariables() {
		$ret = "<pre>";
		$ret .= "_COOKIE";
		if (isset ( $_COOKIE )) {
			$ret .= "<br />";
			foreach ( $_COOKIE as $clave => $valor ) {
				$ret .= "    --> " . $clave . " = " . $valor . "<br />";
			}
		}
		$ret .= "</pre>";
		
		$ret .= "<pre>";
		$ret .= "_ENV";
		if (isset ( $_ENV )) {
			$ret .= "<br />";
			foreach ( $_ENV as $clave => $valor ) {
				$ret .= "    --> " . $clave . " = " . $valor . "<br />";
			}
		}
		$ret .= "</pre>";
		
		$ret .= "<pre>";
		$ret .= "_FILES";
		/*
		 * if (isset($_FILES)) { $ret .= "<br />"; foreach($_FILES as $clave=>$valor) { $ret .= " --> ".$clave." = ".print_r($valor)."<br />"; } }
		 */
		$ret .= "</pre>";
		
		$ret = "<pre>";
		$ret .= "_GET";
		if (isset ( $_GET )) {
			$ret .= "<br />";
			foreach ( $_GET as $clave => $valor ) {
				$ret .= "    --> " . $clave . " = " . $valor . "<br />";
			}
		}
		$ret .= "</pre>";
		
		$ret .= "<pre>";
		$ret .= "_POST";
		if (isset ( $_POST )) {
			$ret .= "<br />";
			foreach ( $_POST as $clave => $valor ) {
				$ret .= "    --> " . $clave . " = " . $valor . "<br />";
			}
		}
		$ret .= "</pre>";
		
		$ret .= "<pre>";
		$ret .= "_REQUEST";
		if (isset ( $_REQUEST )) {
			$ret .= "<br />";
			foreach ( $_REQUEST as $clave => $valor ) {
				$ret .= "    --> " . $clave . " = " . $valor . "<br />";
			}
		}
		$ret .= "</pre>";
		
		$ret .= "<pre>";
		$ret .= "_SESSION";
		if (isset ( $_SESSION )) {
			$ret .= "<br />";
			foreach ( $_SESSION as $clave => $valor ) {
				$ret .= "    --> " . $clave . " = " . $valor . "<br />";
			}
		}
		$ret .= "</pre>";
		
		$ret .= "<pre>";
		$ret .= "_SERVER";
		if (isset ( $_SERVER )) {
			$ret .= "<br />";
			foreach ( $_SERVER as $clave => $valor ) {
				$ret .= "    --> " . $clave . " = " . $valor . "<br />";
			}
		}
		$ret .= "</pre>";
		return $ret;
	}
	function rutaAbsToRel($rutaAbs) {
		$rutaAbs = dirname ( $rutaAbs ) . "/";
		$rutaAbs = substr ( $rutaAbs, 4, strlen ( $rutaAbs ) );
		$cantidadBarras = "";
		
		for($i = 0; $i < strlen ( $rutaAbs ); $i ++) {
			if (substr ( $rutaAbs, $i, 1 ) == "/") {
				$rutaRel .= "../";
			}
		}
		
		return $rutaRel;
	}
	function showPOST($p) {
		global $IDIOMA, $language;
		global $cAUDIT;
		
		self::AddAudit ( AUDIT_DB_SQL_FETCH, __DIR__, __FILE__, __LINE__, __CLASS__, __METHOD__, __FUNCTION__, $language [$IDIOMA] [62] );
		if (isset ( $p )) {
			foreach ( $p as $clave => $valor ) {
				$r = str_pad ( $clave, 20, " ", STR_PAD_LEFT ) . " -> { " . str_pad ( $valor, 50, " ", STR_PAD_RIGHT ) . " }";
				$cAUDIT->AddAudit ( AUDIT_DB_SQL_FETCH, __DIR__, __FILE__, __LINE__, __CLASS__, __METHOD__, __FUNCTION__, $r );
			}
		}
	}
	
	function URL_Actual() {
		$url = "http://" . $_SERVER ['SERVER_NAME'] . ":" . $_SERVER ['SERVER_PORT'] . $_SERVER ['REQUEST_URI'];
		return $url;
	}
	
	function getFile($pFILE) {
		global $IDIOMA, $language;
		
		$ret = '';
		try {
			$file = fopen ( $pFILE, "r" );
			if (! $file)
				$this->AddAudit ( AUDIT_APP, __DIR__, __FILE__, __LINE__, __CLASS__, __METHOD__, __FUNCTION__, $language [$IDIOMA] [8] . $pFILE );
			else {
				$ret = $ret . "<pre>";
				while ( ! feof ( $file ) ) {
					$ret = $ret . fgets ( $file );
				}
				fclose ( $file );
				$ret = $ret . "</ pre>";
			}
			return $ret;
		} catch ( Exception $e ) {
			$cAUDIT->AddAudit ( AUDIT_EXTEND, __DIR__, __FILE__, __LINE__, __CLASS__, __METHOD__, __FUNCTION__, $e->getMessage () );
		}
		
		return $ret;
	}
	function __construct() {
		global $cAUDIT;
		$cAUDIT->AddAudit ( AUDIT_EXTEND, __DIR__, __FILE__, __LINE__, __CLASS__, __METHOD__, __FUNCTION__, "::constructor (" . __CLASS__ . ")" );
	}
	
	public function getDEVICE_TYPE( &$pDISPOSITIVO ) {
		$pDISPOSITIVO = new Mobile_Detect ();
		$deviceType = ($pDISPOSITIVO->isMobile () ? ($pDISPOSITIVO->isTablet () ? CONNECT_TABLET : CONNECT_MOVIL) : CONNECT_WEB);
		
		return $deviceType;
	}

	public function getDEVICE_VAR ( $pMODO ) {
		
	  // Llamada para comprobar que dispositivo es
	  $pTIPO = $this->getDEVICE_TYPE( $pDISPOSITIVO );	
	
    switch ($pMODO) {
        case 0:
            $ret = $pTIPO;
            break;
        case 1:
            $ret =  htmlentities ( $_SERVER ['HTTP_USER_AGENT'] );
            break;
        case 2:
						$ret = '';
						foreach ( $pDISPOSITIVO->getRules () as $name => $regex ) :
							$check = ($pDISPOSITIVO->{'is' . $name} ()) ? 'YES' : 'NO';
							if ($check !== "NO") :
								$ret .= "[is" . $name . ": " . $check . "] - ";
							endif;
						endforeach
						;
		
						foreach ( $pDISPOSITIVO->getProperties () as $name => $match ) :
							$check = $pDISPOSITIVO->version ( $name );
							if ($check !== false) :
								$ret .= "[Version(" . $name . "): " . $check . "] - ";
			
						endif;
						endforeach
						;
            break;
    }
    
    return $ret;
	}
	
	public function getDEVICE() {
		global $cAUDIT;
		global $IDIOMA, $language;
		
	  $ret = '';
		$ret .= "[Type: " . $this->getDEVICE_VAR ( 0 ) . "] - ";
		$ret .= "[HTTP_USER_AGENT: " . $this->getDEVICE_VAR ( 1 ) . "] - ";
		
		// Llamada para comprobar que dispositov es
	  $pTIPO = $this->getDEVICE_TYPE( $pDISPOSITIVO );	
	  
	 	$scriptVersion = $pDISPOSITIVO->getScriptVersion ();
    $scriptName = $pDISPOSITIVO->getScriptName ();
	  
	  $ret .= $this->getDEVICE_VAR ( 2 ) ;
		
		$cAUDIT->AddAudit ( AUDIT_APP, __DIR__, __FILE__, __LINE__, __CLASS__, __METHOD__, __FUNCTION__, "EXTERNAL: " . $scriptName . " - " . $scriptVersion . " " . $ret );
	}

	public function getCAPTCHA() {
		global $cAUDIT;
		global $IDIOMA, $language;
		
		// session_start();
		
		$captcha = new SimpleCaptcha ();
		
		$scriptVersion = $captcha->getScriptVersion ();
		$scriptName = $captcha->getScriptName ();
		
		$cAUDIT->AddAudit ( AUDIT_APP, __DIR__, __FILE__, __LINE__, __CLASS__, __METHOD__, __FUNCTION__, "EXTERNAL: " . $scriptName . " - " . $scriptVersion );
		
		// OPTIONAL Change configuration...
		// $captcha->wordsFile = 'words/es.php';
		$captcha->session_var = 'license';
		$captcha->imageFormat = 'png';
		// $captcha->lineWidth = 3;
		// $captcha->scale = 3;
		$captcha->blur = true;
		$captcha->backgroundColor = array (
				rand ( 0, 255 ),
				rand ( 0, 255 ),
				rand ( 0, 255 ) 
		);
		// $captcha->resourcesPath = "/var/cool-php-captcha/resources";
		
		// OPTIONAL Simple autodetect language example
		
		if (! empty ( $_SERVER ['HTTP_ACCEPT_LANGUAGE'] )) {
			$langs = array (
					'en',
					'es' 
			);
			$lang = substr ( $_SERVER ['HTTP_ACCEPT_LANGUAGE'], 0, 2 );
			if (in_array ( $lang, $langs )) {
				$captcha->wordsFile = "words/$lang.php";
			}
		}
		
		/**
		 * SimpleCaptcha class
		 */
		
		// Image generation
		ob_start ();
		
		$captcha->CreateImage ();
		$image = ob_get_contents ();
		
		ob_end_clean ();
		
		$cAUDIT->AddAudit ( AUDIT_APP, __DIR__, __FILE__, __LINE__, __CLASS__, __METHOD__, __FUNCTION__, "EXTERNAL: " . $scriptName . " - " . $scriptVersion . " Captcha: '" . $_SESSION ['license'] . "'" );
		
		return $image;
	}
	
	public function JSONprettyPrint( $json )
	{
	    $result = '';
	    $level = 0;
	    $prev_char = '';
	    $in_quotes = false;
	    $ends_line_level = NULL;
	    $json_length = strlen( $json );
	
	 		$result .= "\n         | ";
	
	    for( $i = 0; $i < $json_length; $i++ ) {
	        $char = $json[$i];
	        $new_line_level = NULL;
	        $post = "";
	        if( $ends_line_level !== NULL ) {
	            $new_line_level = $ends_line_level;
	            $ends_line_level = NULL;
	        }
	        if( $char === '"' && $prev_char != '\\' ) {
	            $in_quotes = !$in_quotes;
	        } else if( ! $in_quotes ) {
	            switch( $char ) {
	                case '}': case ']':
	                    $level--;
	                    $ends_line_level = NULL;
	                    $new_line_level = $level;
	                    break;
	
	                case '{': case '[':
	                    $level++;
	                case ',':
	                    $ends_line_level = $level;
	                    break;
	
	                case ':':
	                    $post = " ";
	                    break;
	
	                case " ": case "\t": case "\n": case "\r":
	                    $char = "";
	                    $ends_line_level = $new_line_level;
	                    $new_line_level = NULL;
	                    break;
	            }
	        }
	        if( $new_line_level !== NULL ) {
	            $result .= "\n         | ".str_repeat( "\t", $new_line_level );
	        }
	        $result .= $char.$post;
	        $prev_char = $char;
	    }
	
	    return $result;
		}
		
		public function EnviarMail ( $username, $password, $url_activated, $ip_address ) {
		  
		  global $cAUDIT;
		  global $IDIOMA, $language;
				
			$mail             = new PHPMailer();
			$body             = "";

		  $scriptVersion = $mail->getScriptVersion ();
		  $scriptName = $mail->getScriptName ();
		  
		  $cAUDIT->AddAudit ( AUDIT_APP, __DIR__, __FILE__, __LINE__, __CLASS__, __METHOD__, __FUNCTION__, $language [$IDIOMA] [105] . $username . " ..." );
 
			// Cuerpo del Mensaje
			$body .= "<body style='margin: 10px;'>";
			$body .= "<div style='width: 640px; font-family: Arial, Helvetica, sans-serif; font-size: 11px;'>";
			$body .= " <div align='center'>";
			$body .= " <img src='../images/imarkket.png'></div>";
			$body .= " <br /><br><b>Welcome to ".APPLICATION_NAME.".</b><br />";
			$body .= " <br />";
			$body .= " Dear user, Welcome to <b>".APPLICATION_NAME."</b>. You are one step away from having an active user account on the <b>".APPLICATION_NAME."</b> network.";
			$body .= " <br />";
			$body .= " The details provided when you signed up were: <br />";
			$body .= " <br />";
			$body .= " <b>Username</b>: <font color='blue'>$username</font><br />";
			$body .= " <b>Password</b>: <font color='red'>$password</font><br />";
			$body .= " ";
			$body .= " To activate your account, simple click on the URL below <b>before 2 hours (".date ( "d/m/Y - G:ia", (time () + (60*60*2)) ).")</b>:<br />";
			$body .= " $url_activated<br />";
			$body .= " <br />";
			$body .= " Either you, or someone with the IP Address: $ip_address requested an account on our system.";
			$body .= " <br />";
			$body .= " Interactua Development,<br />";
			$body .= " <a href='http://".APPLICATION_WEB_DOMAIN."'>".APPLICATION_WEB_DOMAIN."</a><br />";
			$body .= " <br />";
			$body .= "</div>";
			$body .= "</body>";
			// Fin del Cuerpo del Mensaje

			$mail->IsSMTP();
			$mail->SMTPAuth   = MAILSMTPAuth;                  // enable SMTP authentication
			$mail->SMTPSecure = MAILSMTPSecure;                 // sets the prefix to the servier
			$mail->Host       = MAILHost;      // sets GMAIL as the SMTP server
			$mail->Port       = MAILPort;                   // set the SMTP port

			$mail->Username   = MAILUsername;  // GMAIL username
			$mail->Password   = MAILPassword;  // GMAIL password

			$mail->From       = MAILFrom;
			$mail->FromName   = MAILFromName;
			$mail->Subject    = MAILSubject;
			$mail->AltBody    = MAILAltBody; //Text Body
			$mail->WordWrap   = MAILWordWrap; // set word wrap

			$mail->MsgHTML($body);

			$mail->AddReplyTo(MAILAddReplyToEmail, MAILAddReplyToName);

			$mail->AddAttachment("../../images/imarkket.png");             // attachment

			$mail->AddAddress( $username, "Usuario");

			$mail->IsHTML(MAILisHTML); // send as HTML
			
			$mail->SMTPDebug  = MAILSMTPDebug;
			
			if(!$mail->Send()) {
			  $cAUDIT->AddAudit ( AUDIT_APP, __DIR__, __FILE__, __LINE__, __CLASS__, __METHOD__, __FUNCTION__, "EXTERNAL: " . $scriptName . " - " . $scriptVersion . " " . $language [$IDIOMA] [105] . $username . " " . $language [$IDIOMA] [93] . $mail->ErrorInfo );
        return -1;
			} else {
			  $cAUDIT->AddAudit ( AUDIT_APP, __DIR__, __FILE__, __LINE__, __CLASS__, __METHOD__, __FUNCTION__, "EXTERNAL: " . $scriptName . " - " . $scriptVersion . " " . $language [$IDIOMA] [105] . $username . " ok" );
       return 0;
			}
		}
		
}
;

// Instancia de la clase
try {
	// Instancia de la clase
	$cUTIL = c_krn_utils::getInstance ();
} catch ( Exception $e ) {
	global $IDIOMA, $language;
	echo $language [$IDIOMA] [59] . $e->getMessage ();
}

?>
